<template>
  <AdminHeader></AdminHeader>
    <div class="admin-novels">
      <div class="search-bar">
          <el-select v-model="searchType" placeholder="请选择搜索类型" class="search-type">
            <el-option label="书名" value="1"></el-option>
          </el-select>
          <el-input v-model="searchInput" @keydown.enter="search" placeholder="请输入搜索内容" class="search-input"></el-input>
          <el-button type="primary" @click="search">搜索</el-button>
      </div>
      <el-button type="success" @click="addNovel()">+ 增加小说</el-button>
      <el-table :data="filteredNovels.length ? filteredNovels : novels" stripe style="width: 100%" class="novel-table">
        <el-table-column prop="novel_id" label="ID"></el-table-column>
        <el-table-column prop="novel_name" label="书名"></el-table-column>
        <el-table-column label="描述">
          <template #default="scope">
            {{ truncate(scope.row.novel_desc) }}
          </template>
        </el-table-column>
        <el-table-column prop="novel_type" label="类型"></el-table-column>
        <el-table-column prop="novel_author.nickname" label="作者"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="info" size="small" @click="goToRead(scope.row.novel_id)">阅读</el-button>
            <el-button type="warning" size="small" @click="editChapter(scope.row.novel_id)">章节</el-button>
            <el-button type="primary" size="small" @click="editNovel(scope.row.novel_id)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteNovel(scope.row.novel_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <div class="pagination-container" v-if="!isSearching">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, prev, pager, next, jumper"
            :total="totalNovels"
            class="pagination">
        </el-pagination>
      </div>
    </div>
  </template>
  
  <script lang="js">
  import { ref, onMounted } from 'vue';
  import axios from 'axios';
  import VueCookies from "vue-cookies";
  import AdminHeader from "@/components/AdminHeader.vue";
  import {ElMessageBox, ElNotification} from "element-plus";
  import router from "@/router/index.js";
  import config from "../../../config/config.js";
  
  export default {
    components: {
      AdminHeader,
    },
    setup() {
      const novels = ref([]);
      const totalNovels = ref(0);
      const currentPage = ref(1);
      const pageSize = ref(1);
      const searchInput = ref('');
      const searchType = ref('1'); // 默认搜索类型为用户名
      const filteredNovels = ref([]);
      const adminToken = VueCookies.get('adminToken');
      const isSearching = ref(false);
  
      const fetchNovels = async () => {
        try {
          const response = await axios.get(`${config.apiUrl}/novel/all?page=${currentPage.value}`, {
            headers: {
              Authorization: `Bearer ${adminToken}`
            }
          });
          novels.value = response.data.novels;
          totalNovels.value = response.data.totalPages;
        } catch (error) {
          console.error('Error fetching novels:', error);
        }
      };
  
      const search = async () => {
        isSearching.value = true;
        filteredNovels.value = []; // 清空搜索结果
        const apiUrl = `${config.apiUrl}/novel/search?novelName=${searchInput.value}`;
        try {
          const response = await axios.get(apiUrl, {
            headers: {
              Authorization: `Bearer ${adminToken}`
            }
          });
          if (response.data && response.data.length > 0) {
            filteredNovels.value = response.data;
          }else{
            filteredNovels.value = response.data;
            ElNotification({
              message: "没找到："+searchInput.value+" ！",
              type: 'warning',
              duration: 1000
            });
          }
        } catch (error) {
          console.error('Error searching novels:', error);
        }
      };
  

      const handleSizeChange = (val) => {
        pageSize.value = val;
        fetchNovels();
      };
  
      const handleCurrentChange = (val) => {
        currentPage.value = val;
        fetchNovels();
      };
      const editNovel = (novelId) => {
        router.push('/admin/editnovel/'+novelId);
      };
      const editChapter = (novelId) => {
        router.push('/admin/chapter/search/'+novelId);
      };
      const addNovel = () => {
        router.push('/admin/addnovel/');
      };
      const goToRead = (novelId) => {
        router.push('/novel/'+novelId);
      };
  
      const deleteNovel = async (novelId) => {
        try {
          // 弹出确认对话框
          await ElMessageBox.confirm('确定要删除该小说吗？会连同章节一并删除！', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          });
          // 用户确认删除后执行删除操作
          const apiUrl = `${config.apiUrl}/novel/delete?novelId=${novelId}`;
          const response = await axios.get(apiUrl, {
            headers: {
              Authorization: `Bearer ${adminToken}`
            }
          });
          ElNotification({
            message: "删除成功！",
            type: 'success',
            duration: 1000
          });
          // 删除成功后更新用户列表数据
          if (searchInput.value) {
            await search();
          } else {
            // 否则，更新用户列表数据
            await fetchNovels();
          }
        } catch (error) {
          console.error('Error delete novel:', error);
        }
      };

      const truncate = (text) => {
        if (!text) return '';
        return text.length > 40 ? text.substring(0, 30) + '...' : text;
      };

      onMounted(() => {
        fetchNovels();
      });
  
  
  
      return {
        novels,
        totalNovels,
        currentPage,
        pageSize,
        searchInput,
        searchType,
        filteredNovels,
        truncate,
        search,
        handleSizeChange,
        handleCurrentChange,
        editNovel,
        deleteNovel,
        addNovel,
        goToRead,
        editChapter,
        isSearching,
      };
    },
  };
  </script>
  
  <style scoped>
  .admin-novels {
    padding: 20px;
  }
  
  .search-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
  }
  
  .search-type {
    width: 100px;
    margin-right: 10px;
  }
  
  .search-input {
    width: 80%;
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    flex-wrap: wrap; /* 允许弹性项目在需要时换行 */
  }
  .pagination {
     max-width: 100%; /* 限制宽度为父容器的100% */
     overflow-x: auto; /* 如果内容超出宽度，则显示水平滚动条 */
   }


  .novel-table {
    margin-top: 20px;
  }
  </style>
  